<?php
/*========================================= JooSam =========================================/
/																							/
/	Extention:		JooSam																	/
/	Created by:		Broadcastweb.eu - Paules												/
/	Site:			http://www.broadcastweb.eu												/
/	Email:			support@broadcastweb.eu													/
/	Copyright:		2011 - 2012 (c) Broadcastweb.eu											/
/	License:		CC BY-NC-ND 3.0 ~ http://creativecommons.org/licenses/by-nc-nd/3.0/		/
/	File Version:	0003																	/
/																							/
/========================================== JooSam ========================================*/
// Joomla Security
defined('_JEXEC') or die;

class jsm_get{

	// Pagenation for frontend
	public function pagenation($table){

		$jsm_helper = new JooSamHelper();
		$settings = $jsm_helper->config();
		$params = $jsm_helper->Params();
	
		if($table == 'songlist'){
			$search_data = JRequest::getVar('jsm_hidden_searchdata', '');
			if($search_data == 'nolet' or $search_data == ''){
				$gosearch = '%';
			} else{
				$gosearch = $search_data.'%';
			}
			$cat_view = $settings->request->category_view;
			$songtype = $settings->request->songtype;
			$query = "	SELECT S.ID, S.artist, S.title
						FROM songlist S, categorylist C
						WHERE (S.artist LIKE '".$gosearch."')
						AND C.categoryID IN(".$cat_view.")
						AND S.songtype IN(".$songtype.")
						AND S.ID = C.songID
						ORDER BY S.artist, S.title ASC
					";
		}
		else{
			$query = 'SELECT * FROM '.$table;
		}
		$limit = JRequest::getVar('jsm_row_limit', 20);
		$page = JRequest::getVar('jsm_hidden_pagenum', 0);
		$db = new samdbo();
		$rows = $db->countRows($query);
		$pages = ceil($rows / $limit);
		$cpage = $page+1;
		$html = '		<div class="jsm_pagenation" style="text-align:center;">';
		$html .= '			<span class="jsm_pageinfo" style="float:left;">'.JText::_('COM_JOOSAM_PAGE').':'.$cpage.'/'.$pages.'</span>';
		if($params->table->buttons->activate_buy != 'show'){
			$html .= '		<div class="jsm_pageselect" style="float:right;">';
			$html .= '			<span class="jsm_label">'.JText::_('COM_JOOSAM_DISPLAY').':</span>';
			$html .= '			<select name="jsm_row_limit" id="jsm_row_limit" onchange="joosam.setpagelimit();">';
			$html .= '				<option value="'.$limit.'">'.$limit.'</option>';
			$html .= '				<option value="5">5</option>';
			$html .= '				<option value="10">10</option>';
			$html .= '				<option value="20">20</option>';
			$html .= '				<option value="30">30</option>';
			$html .= '				<option value="50">50</option>';
			$html .= '				<option value="100">100</option>';
			$html .= '			</select>';
			$html .= '		</div>';
		} else{
			$html .=		'<span class="jsm_psel_isbuy" style="float:right; font-size:9px;" title="'.JText::_('COM_JOOSAM_DISPLAY_BUY_TITLE').'">'.JText::_('COM_JOOSAM_DISPLAY_HIDDEN').'</span>';
		}
		$html .= '			<div class="jsm_pageseletfull" style="text-align:center; margin:0 auto;">';
		if($pages > 1){
			$goPrev = $page -1;
			if($goPrev < 0){ $goPrev = 0; }
			$html .= '			<button class="jsm_pageFirst" onclick="joosam.gopage(\'0\'); return false;"> &lt; '.JText::_('COM_JOOSAM_GOFIRST').' </button>';
			$html .= '			<button class="jsm_pagePrev" onclick="joosam.gopage(\''.$goPrev.'\'); return false;"> &lt;&lt;&lt; </button>';
			$counter = 0;
			$html .= '			<span class="jsm_pageselet">';
			// Count Pages We show
			$total_pages = $pages;
			$curent_page = $page;
			$first_page = $curent_page - 4;
			$last_page = $curent_page + 4;
			$last_load = $curent_page + 4;
			if($first_page <= 0){
				$start = 0;
			}
			else{
				$start = $first_page;
			}
			if($last_load <= 7){
				$last_page = 8;
			}
			if($last_page >= $total_pages){
				$end = $total_pages;
			}
			else{
				$end = $last_page;
			}
			
			while($start < $end){
				
				$pagecount = $start;
				$start = $start + 1;
				$html .= '			<a class="pageGo" onclick="joosam.gopage(\''.$pagecount.'\'); return false;" id="apage'.$start.'">'.$start.'</a> ';
			}
			$html .= '			</span>';
			$goNext = $page +1;
			if($goNext >= $pages){ $goNext = $pages - 1; }
			$lastpage_go = $total_pages - 1;
			$html .= '			<button class="jsm_pageNext" onclick="joosam.gopage(\''.$goNext.'\'); return false;"> &gt;&gt;&gt; </button>';
			$html .= '			<button class="jsm_pageLast" onclick="joosam.gopage(\''.$lastpage_go.'\'); return false;"> '.JText::_('COM_JOOSAM_GOLAST').' &gt; </button>';
		} else{
			$html .= '			<span style="line-height:22px;">&nbsp;</span>';
		}
		$html .= '			</div>';
		$html .= '		</div>';
		return $html;
	}

	// Function ranking stars
	public function rankStars($rank){

		$jsm_helper = new JooSamHelper();
		$settings = $jsm_helper->Params();
		$star = $settings->table->rating_color;

		$html = '<span class="jsm_ranking_inner" title="Rank: '.$rank.'">';
		$img0 = '<img src="media/com_joosam/images/stars/star0_'.$star.'.png" class="jsm_rankstar" border="0" width="16" height="16" />';
		$img1 = '<img src="media/com_joosam/images/stars/star01_'.$star.'.png" class="jsm_rankstar" border="0" width="16" height="16" />';
		$img2 = '<img src="media/com_joosam/images/stars/star1_'.$star.'.png" class="jsm_rankstar" border="0" width="16" height="16" />';
		// Star1
		if($rank >= 2){ $star1 = $img2; }
		else if($rank == 1){ $star1 = $img1; }
		else{ $star1 = $img0; }
		// Star2
		if($rank >= 4){ $star2 = $img2; }
		else if($rank == 3){ $star2 = $img1; }
		else{ $star2 = $img0; }
		// Star3
		if($rank >= 6){ $star3 = $img2; }
		else if($rank == 5){ $star3 = $img1; }
		else{ $star3 = $img0; }
		// Star4
		if($rank >= 8){ $star4 = $img2; }
		else if($rank == 7){ $star4 = $img1; }
		else{ $star4 = $img0; }
		// Star5
		if($rank >= 9){ $star5 = $img2; }
		else{ $star5 = $img0; }
		$html .= $star1.$star2.$star3.$star4.$star5;
		$html .= '</span>';
		return $html;
	}

	// Load song image
	public function jsm_songimage($songid){

		$jsm_helper = new JooSamHelper();
		$settings = $jsm_helper->config();
		$params = $jsm_helper->Params();
		$error = false;
		$img_width = $params->extrainfo->image_width;
		$img_height = $params->extrainfo->image_height;
		//Get sql Data
		$db = new samdbo();
		$query = "SELECT * FROM songlist WHERE ID = $songid;";
		$sqldata = $db->getObjectList($query);
		if(is_array($sqldata)){
			$songdata = $sqldata[0];
		} else{
			$songdata = $sqldata;
		}
		$artist = utf8_encode($songdata->artist);
		$picture = $songdata->picture;
		$type = $settings->image->source;

		// Load from last.fm
		if($type == 0){
			if(function_exists('curl_init')){
				$lfm_host = 'http://ws.audioscrobbler.com/2.0/';
				$lfm_artist = urlencode($artist);
				$lfm_method = 'artist.getinfo';
				$lfm_apikey = $settings->image->data;
				$lfm_url = $lfm_host.'?method='.$lfm_method.'&artist='.$lfm_artist.'&api_key='.$lfm_apikey;
				$srv = curl_init($lfm_url);
				curl_setopt($srv, CURLOPT_HEADER, false);
				curl_setopt($srv, CURLOPT_RETURNTRANSFER, true);
				$response = curl_exec($srv);
				curl_close($srv);
				if($response == ''){
					$error = true;
					$data = JText::_('COM_JOOSAM_IMG_ERR_LFMCONNECT');
				} else{
					$header = array();
					preg_match('/\d\d\d/', $response, $header);
					$header[] = 'placeholder';
					if($header[0] == 404){
						$error = true;
						$data = JText::_('COM_JOOSAM_IMG_ERR_LFM404');
					} else{
						$xml = simplexml_load_string($response);
						$status = $xml->attributes()->status;
						if($status == 'failed'){
							$error = true;
							$data = $xml->error;
						} else if($status == 'ok'){
							$image = $xml->artist[0]->image[4];
							if($image == ''){$image = $xml->artist[0]->image[3];}
							if($image == ''){$image = $xml->artist[0]->image[2];}
							if($image == ''){$image = $xml->artist[0]->image[1];}
							if($image == ''){$image = false;}
							if($image){
								$data = $image;
							} else{
								$error = true;
								$data = JText::_('COM_JOOSAM_IMG_ERR_NOIMG');
							}
						} else{
							$error = true;
							$data = JText::_('COM_JOOSAM_IMG_ERR_LFMRESPONSE');
						}
					}
				}
			} else{
				$error = true;
				$data = JText::_('COM_JOOSAM_ERR_PHP_NOCURL');
			}
		}
		// Load from folder. (not tested)
		else{
			if($settings->image->data != ''){
				$url = $settings->image->data.$picture;
				if(file_exists($url)){
					$data = $url;
				} else{
					$error = true;
					$data = JText::_('COM_JOOSAM_IMG_ERR_LOCALURL').$url;
				}
			} else{
				$error = true;
				$data = JText::_('COM_JOOSAM_IMG_ERR_NOPATHLOAD');
			}
		}

		if($error){
			$result = '<p>'.$data.'</p>';
		} else{
			if($img_width == 'px'){$img_width = '{load_width}';}
			if($img_height == 'px'){$img_height = '{load_height}';}
			$result = '<img src="'.$data.'" width="'.$img_width.'" height="'.$img_height.'" border="0" class="jsm_songimage" />';
		}

		return $result;
	}

	public function jsm_buybutton($artist, $title, $songid){

		$jsm_helper = new JooSamHelper();
		$settings = $jsm_helper->config();
		$params = $jsm_helper->Params();
		$lastfm = $settings->image->source;
		if($lastfm == 0){
			if(function_exists('curl_init')){
				$lfm_host = 'http://ws.audioscrobbler.com/2.0/';
				$lfm_artist = urlencode($artist);
				$lfm_title = urlencode($title);
				$lfm_method = 'track.getbuylinks';
				$lfm_country = urlencode('united states');
				$lfm_apikey = $settings->image->data;
				$lfm_url = $lfm_host.'?method='.$lfm_method.'&artist='.$lfm_artist.'&track='.$lfm_title.'&country='.$lfm_country.'&api_key='.$lfm_apikey;
				$srv = curl_init($lfm_url);
				curl_setopt($srv, CURLOPT_HEADER, false);
				curl_setopt($srv, CURLOPT_RETURNTRANSFER, true);
				$response = curl_exec($srv);
				curl_close($srv);
				if($response == ''){
					$result = '<button class="jsm_button" onclick="return false;" title="'.JText::_('COM_JOOSAM_IMG_ERR_LFMCONNECT').'" readonly>'.JText::_('COM_JOOSAM_ERROR').'</button>';
				} else{
					$header = array();
					preg_match('/\d\d\d/', $response, $header);
					$header[] = 'placeholder';
					if($header[0] == 404){
						$result = '<button class="jsm_button" onclick="return false;" debug="'.$lfm_url.'" title="'.JText::_('COM_JOOSAM_IMG_ERR_LFM404').'" readonly>Error</button>';
					} else{
						$xml = simplexml_load_string($response);
						$status = $xml->attributes()->status;
						if($status == 'failed'){
							$result = '<button class="jsm_button" onclick="return false;" title="'.$xml->error.'" readonly>'.JText::_('COM_JOOSAM_ERROR').'</button>';
						} else if($status == 'ok'){
							$outp = '<select style="width:60px;" name="gobuy_track" id="gobuy_track_'.$songid.'" onchange="joosam.gobuytrack(\''.$songid.'\');">';
							$outp .= '<option value="error">'.JText::_('COM_JOOSAM_BUY').'</option>';
							if(is_object($xml->affiliations[0]->physicals[0]->affiliation[0])){
								$phys1_name = $xml->affiliations[0]->physicals[0]->affiliation[0]->supplierName[0];
								$phys1_link = $xml->affiliations[0]->physicals[0]->affiliation[0]->buyLink[0];
								if($phys1_name == ''){$phys1_name = 'JunoDownload';}
								$outp .= '<option value="'.$phys1_link.'">'.$phys1_name.'</option>';
							}
							if(is_object($xml->affiliations[0]->physicals[0]->affiliation[1])){
								$phys2_name = $xml->affiliations[0]->physicals[0]->affiliation[1]->supplierName[0];
								$phys2_link = $xml->affiliations[0]->physicals[0]->affiliation[1]->buyLink[0];
								if($phys2_name == ''){$phys2_name = 'JunoDownload';}
									$outp .= '<option value="'.$phys2_link.'">'.$phys2_name.'</option>';
							}
							if(is_object($xml->affiliations[0]->physicals[0]->affiliation[2])){
								$phys3_name = $xml->affiliations[0]->physicals[0]->affiliation[2]->supplierName[0];
								$phys3_link = $xml->affiliations[0]->physicals[0]->affiliation[2]->buyLink[0];
								if($phys3_name == ''){$phys3_name = 'JunoDownload';}
								$outp .= '<option value="'.$phys3_link.'">'.$phys3_name.'</option>';
							}
							if(is_object($xml->affiliations[0]->downloads[0]->affiliation[0])){
								$down1_name = $xml->affiliations[0]->downloads[0]->affiliation[0]->supplierName[0];
								$down1_link = $xml->affiliations[0]->downloads[0]->affiliation[0]->buyLink[0];
								if(is_object($xml->affiliations[0]->downloads[0]->affiliation[0]->price[0])){
									$down1_curr = $xml->affiliations[0]->downloads[0]->affiliation[0]->price[0]->currency[0];
									$down1_price = $xml->affiliations[0]->downloads[0]->affiliation[0]->price[0]->amount[0];
									$down1_costs = '('.$down1_curr.': '.$down1_price.')' ;
								} else{
									$down1_costs = '';
								}
								$down1_icon = $xml->affiliations[0]->downloads[0]->affiliation[0]->supplierIcon[0];
								if($down1_name == ''){$down1_name = 'JunoDownload';}
								$outp .= '<option value="'.$down1_link.'">'.$down1_name.' '.$down1_costs.' </option>';
							}
							if(is_object($xml->affiliations[0]->downloads[0]->affiliation[1])){
								$down2_name = $xml->affiliations[0]->downloads[0]->affiliation[1]->supplierName[0];
								$down2_link = $xml->affiliations[0]->downloads[0]->affiliation[1]->buyLink[0];
								if(is_object($xml->affiliations[0]->downloads[0]->affiliation[1]->price[0])){
									$down2_curr = $xml->affiliations[0]->downloads[0]->affiliation[1]->price[0]->currency[0];
									$down2_price = $xml->affiliations[0]->downloads[0]->affiliation[1]->price[0]->amount[0];
									$down2_costs = '('.$down2_curr.': '.$down2_price.')' ;
								} else{
									$down2_costs = '';
								}
								$down2_icon = $xml->affiliations[0]->downloads[0]->affiliation[1]->supplierIcon[0];
								if($down2_name == ''){$down2_name = 'JunoDownload';}
								$outp .= '<option value="'.$down2_link.'">'.$down2_name.' '.$down2_costs.' </option>';
							}
							if(is_object($xml->affiliations[0]->downloads[0]->affiliation[2])){
								$down3_name = $xml->affiliations[0]->downloads[0]->affiliation[2]->supplierName[0];
								$down3_link = $xml->affiliations[0]->downloads[0]->affiliation[2]->buyLink[0];
								if(is_object($xml->affiliations[0]->downloads[0]->affiliation[2]->price[0])){
									$down3_curr = $xml->affiliations[0]->downloads[0]->affiliation[2]->price[0]->currency[0];
									$down3_price = $xml->affiliations[0]->downloads[0]->affiliation[2]->price[0]->amount[0];
									$down3_costs = '('.$down3_curr.': '.$down3_price.')' ;
								} else{
									$down3_costs = '';
								}
								$down3_icon = $xml->affiliations[0]->downloads[0]->affiliation[2]->supplierIcon[0];
								if($down3_name == ''){$down3_name = 'JunoDownload'; }
								$outp .= '<option value="'.$down3_link.'">'.$down3_name.' '.$down3_costs.' </option>';
							}
							$outp .= '</select>';
							$result = $outp;
						} else{
							$result = '<button class="jsm_button" onclick="return false;" title="'.JText::_('COM_JOOSAM_IMG_ERR_LFMRESPONSE').'" readonly>'.JText::_('COM_JOOSAM_ERROR').'</button>';
						}
					}
				}
			} else{
				$result = '<button class="jsm_button" onclick="return false;" title="'.JText::_('COM_JOOSAM_ERR_PHP_NOCURL').'" readonly>'.JText::_('COM_JOOSAM_ERROR').'</button>';
			}
		}else{
			$result = '<button class="jsm_button" onclick="return false;" title="'.JText::_('COM_JOOSAM_BUY_NO_LFM_SUPPORT').'" readonly>'.JText::_('COM_JOOSAM_ERROR').'</button>';
		}
		return $result;
	}

	public function jsm_requestmsg($rid){

		$db = new samdbo();
		$jsm_helper = new JooSamHelper();
		$settings = $jsm_helper->config();
		$params = $jsm_helper->Params();
		$query = "SELECT msg, name FROM requestlist WHERE ID = '".$rid."'";
		$sqldata = $db->getObjectList($query);
		if(is_array($sqldata)){
			$reqdata = $sqldata[0];
		} else{
			$reqdata = $sqldata;
		} if($reqdata){
			$result = (object) array(
								'name' => $reqdata->name,
								'msg' => $reqdata->msg
						);
		} else{
			$result = (object) array(
								'name' => '',
								'msg' => ''
						);
		}
		return $result;
	}

	public function jsm_curplayed(){

		$db = new samdbo();
		$jsm_helper = new JooSamHelper();
		$settings = $jsm_helper->config();
		$params = $jsm_helper->Params();

		// Build
		$timeZone = $settings->server->timezone;
		$stzone = date_default_timezone_get();
		if($stzone != $timeZone){ date_default_timezone_set($timeZone); }
		$time = strtotime('now');
		$date = date('Y-m-d H:i:s');
		$query = "	SELECT picture, songID, date_played, duration, artist, title, requestID
					FROM historylist
					WHERE UNIX_TIMESTAMP(date_played)+(duration/1000) > $time
					ORDER BY ID DESC
					LIMIT 0, 1
				";
		$sqldata = $db->getObjectList($query);
		if(is_array($sqldata)){
			$songdata = $sqldata[0];
		} else{
			$songdata = $sqldata;
		} if($songdata){
			$artist = utf8_encode($songdata->artist);
			$title = utf8_encode($songdata->title);
			$request = $songdata->requestID;
			$songid = $songdata->songID;
			$image = jsm_get::jsm_songimage($songid);
			$duration = $songdata->duration;
			$played = $songdata->date_played;
			if($request > 0){
				$req = jsm_get::jsm_requestmsg($request);
				$req_name = $req->name;
				$req_msg = $req->msg;
			}else{
				$req_name = '';
				$req_msg = '';
			}

			$result = (object) array(
								'artist' => $artist,
								'title' => $title,
								'songid' => $songid,
								'image' => $image,
								'duration' => $duration,
								'played' => $played,
								'datetime' => $date,
								'request' => $request,
								'request_name' => $req_name,
								'request_msg' => $req_msg
						);
			return $result;
		} else{
			return false;
		}
	}

	public function jsm_history(){

		$db = new samdbo();
		$jsm_helper = new JooSamHelper();
		$settings = $jsm_helper->config();
		$params = $jsm_helper->Params();
		$songtype = $settings->request->songtype;
		// Build
		$timeZone = $settings->server->timezone;
		$stzone = date_default_timezone_get();
		if($stzone != $timeZone){ date_default_timezone_set($timeZone); }
		$time = strtotime('now');
		$date = date('Y-m-d H:i:s');
		$query = "	SELECT songID, date_played, artist, title
					FROM historylist
					WHERE UNIX_TIMESTAMP(date_played)+(duration/1000) < $time
					AND songtype IN (".$songtype.")
					ORDER BY ID DESC
					LIMIT 0, 10
				";
		$sqldata = $db->getObjectList($query);
		if(is_array($sqldata)){
			foreach($sqldata as $songdata){
		 		$artist = utf8_encode($songdata->artist);
				$title = utf8_encode($songdata->title);
				$played = $songdata->date_played;
				$songid = $songdata->songID;
				$result[] = (object) array( 'artist' => $artist, 'title' => $title, 'played' => $played, 'songid' => $songid );
			}
			return $result;
		} else{
			return false;
		}
	}

	public function jsm_queue(){

		$db = new samdbo();
		$jsm_helper = new JooSamHelper();
		$settings = $jsm_helper->config();
		$params = $jsm_helper->Params();

		// Build
		$timeZone = $settings->server->timezone;
		$stzone = date_default_timezone_get();
		if($stzone != $timeZone){ date_default_timezone_set($timeZone); }
		$time = strtotime('now');
		$date = date('Y-m-d H:i:s');
		$query = "	SELECT S.ID, S.artist, S.title
					FROM songlist S, queuelist Q
					WHERE S.ID = Q.songID
					ORDER BY Q.ID ASC
					LIMIT 0, 5
				";
		$sqldata = $db->getObjectList($query);
		if(is_array($sqldata)){
			foreach($sqldata as $songdata){
		 		$artist = utf8_encode($songdata->artist);
				$title = utf8_encode($songdata->title);
				$songid = $songdata->ID;
				$result[] = (object) array( 'artist' => $artist, 'title' => $title, 'songid' => $songid );
			}
			return $result;
		} else{
			return false;
		}
	}
		
	
	public function jsm_replace($type){

		$jsm_helper = new JooSamHelper();
		$settings = $jsm_helper->config();
		$songid = JRequest::getVar('jsm_hidden_songid', 0);

		//Get sql Data
		$db = new samdbo();
		$query = "SELECT * FROM songlist WHERE ID = $songid;";
		$sqldata = $db->getObjectList($query);
		if(is_array($sqldata)){
			$songdata = $sqldata[0];
		} else{
			$songdata = $sqldata;
		}
		
		$artist = utf8_encode($songdata->artist);
		$picture = $songdata->picture;
		$title = utf8_encode($songdata->title);
		$lyrics = utf8_encode($songdata->lyrics);
		$date_played = $songdata->date_played;
		$rating = $songdata->rating;
		$info = utf8_encode($songdata->info);
		$duration = $songdata->duration;
		//echo '<h2>'.$artist.'</h2>';
		//Image
		if($type == 'loadimage'){
			$result = jsm_get::jsm_songimage($songid);
		}
		// Title
		else if($type == 'loadtitle'){
			$result = $title;
		}
		// Artist
		else if($type == 'loadartist'){
			$result = $artist;
		}
		// SongText
		else if($type == 'loadsongtext'){
			$result = nl2br($lyrics);
		}
		// Date Last played
		else if($type == 'loadplayed'){
			$result = $date_played;
		}
		// Rating
		else if($type == 'loadrating'){
			$result = jsm_get::rankStars($rating);
		}
		// Description
		else if($type == 'loaddescr'){
			$result = nl2br($info);
		}
		// Duration
		else if($type == 'loadduration'){
			$song_duration = round($duration/1000);
			$result = date('i:s',$song_duration);
		}
		// Buy Button
		else if($type == 'loadbuybutton'){
			$result = jsm_get::jsm_buybutton($artist, $title, $songid);
		}
		// Request Button
		else if($type == 'loadrequest'){
			$result = '<button id="jsm_request" onclick="joosam.gorequest(\''.$songid.'\')">Request</button>';
		}
		// Unknown
		else{
			$result = false;
		}
		return $result;
	}
}